<template>
  <div class="app_main">
    <div style="text-align: center;font-size: 25px;font-weight: bold;margin-top: 20px">
      {{ edit ? '编辑方案' : intentionSchemeSave.related_type === 2 ? '补充协议' : '新增方案' }}
    </div>

    <point-config :data="intentionSchemeSave.tmpDataList" :date_range="date_range" :error-data="errorData"
                  :exclude-sale-choose-id="intentionSchemeSave.related_type===2?intentionSchemeSave.exclude_sale_choose_id:null"
                  :has-spec-id="true" :has-date-range-limit="intentionSchemeSave.type === 2"
                  @removeConfig="removeConfig"
                  @removeConfigBuilding="removeConfigBuilding" @setSearchConfig="getSearchConfig"
                  @editConfig="editConfigBuildingData" @showPointList="showPointList"
                  @showOrder="showSelectOrderDialog"/>

    <div style="padding-top: 20px">
      <el-divider content-position="left">基本信息</el-divider>
      <el-form ref="saveForm" :model="intentionSchemeSave" :rules="saveFormRules">
        <el-row style="padding: 0 40px 0 60px">
          <el-col :span="12" style="padding:0 5px">
            <el-form-item label="名称" prop="plan_name">
              <el-input v-model="intentionSchemeSave.plan_name" style="width: 90%" placeholder="请输入方案名称" clearable/>
            </el-form-item>
            <el-form-item label="客户" prop="customer_id">
              <el-select :disabled="customer_id_select_disabled" v-model="intentionSchemeSave.customer_id"
                         style="width: 90%" clearable
                         placeholder="请选择客户" filterable>
                <el-option v-for="item in customer_arr" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="padding:0 5px">
            <el-form-item label="类型">
              <el-select v-model="intentionSchemeSave.plan_type" style="width: 90%" clearable placeholder="请选择方案类型">
                <el-option v-for="item in plan_type_arr" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="intentionSchemeSave.memo" style="width: 90%" type="textarea" :rows="4"
                        placeholder="请输入备注"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!--关联工单弹框-->
    <el-dialog title="工单" :visible.sync="selectOrderDialogVisible" width="20%" center @close="closeSelectOrderDialog">
      <div style="text-align: center">
        <el-form label-width="80" size="mini">
          <el-form-item label="工单">
            <el-select v-model="orderId">
              <el-option v-for="order in orderTableData" :key="order.worker_order_id" :label="order.work_order_name"
                         :value="order.worker_order_id"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="selectOrderDialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="relationWorkOrder">确 定</el-button>
      </span>
    </el-dialog>
    <!--具体点位-->
    <el-dialog title="具体点位" :visible.sync="showPointListDialogVisible" width="40%" center>
      <el-table :data="tmpPointList" size="mini" stripe border>
        <el-table-column min-width="10" label="点位编号" prop="code" align="center"/>
        <el-table-column min-width="20" label="详情" prop="full_detail" align="center" show-overflow-tooltip/>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="showPointListDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="savePlanDialogVisible" width="30%" center append-to-body>
      <div>
        您想以什么方式保存方案
      </div>
      <div style="text-align: right;padding: 10px 0">
        <el-button size="small" @click="savePlanDialogVisible = false">关闭</el-button>
        <el-button v-show="intentionSchemeSave.related_type !== 2" size="small" type="info" @click="notLock">不锁定
        </el-button>
        <el-button size="small" type="primary" @click="lock">锁定</el-button>
      </div>
    </el-dialog>
    <!--冲突提示-->
    <el-dialog title="冲突提示" :visible.sync="conflictDialogVisible" width="30%" center append-to-body
               @close="closeConflictDialog"
    >
      <div>
        点位关联有冲突，请选择关联方式
      </div>
      <div style="text-align: right;padding: 10px 0">
        <el-button size="small" @click="conflictDialogVisible = false">取消关联</el-button>
        <el-tooltip class="item" effect="dark" content="关联工单剩余未关联并且此时间段有的点位" placement="top">
          <el-button size="small" type="info" @click="relationPoint(orderPointArr,configPointArr,false,[])">弱关联
          </el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="移除其他配置项关联并关联到此配置项" placement="top">
          <el-button size="small" type="warning"
                     @click="relationPoint(orderPointArr,configPointArr,true,forcePointArr)"
          >强关联
          </el-button>
        </el-tooltip>
      </div>
    </el-dialog>
    <!--点位搜索弹框组件-->
    <position-selection :date-range="date_range"
                        :config-type="type"
                        :component-type="intentionSchemeSave.type"
                        :has-large-screen-type="true"
                        :response-type="2"
                        :building-list="searchForm.buildingList" :type-switch-disabled="disabled"
                        :exclude-building-id-list="searchForm.exclude_building_id_list"
                        :exclude-media-id-list="searchForm.exclude_media_id_list"
                        :point-type-id-list="searchForm.pointTypeIdList"
                        :exclude-sale-choose-id="intentionSchemeSave.related_type === 2?intentionSchemeSave.exclude_sale_choose_id:null"
                        :dialog-show="positionSelectionDialogVisible"
                        @close="closeSearchDialog"
                        @save="saveConfig"
    />
    <div style="text-align: center;padding-bottom: 20px">
      <el-button size="mini" @click="closeThisPage">退出</el-button>
      <el-button v-if="billSaleStatus !== 3 && billSaleStatus!==4" size="mini" type="primary" @click="save(false)">保存
      </el-button>
      <el-button v-if="edit" size="mini" type="primary" @click="save(true)">保存成新方案</el-button>
    </div>
  </div>
</template>

<script>
import { list_all3rd_bycode } from '@/api/business/setting/dict'
import {
  area_list,
  list_all,
  list_floor_selections,
  list_media_types,
  search_address_by_page
} from '@/api/building/building'
import { company_list_all } from '@/api/customer/customer'
import {detail as planDetail, detail, lock, save, search} from '@/api/business/intention_scheme'
import { detail as saleOrderDetail } from '@/api/saleOrder/'
import positionSelection from '@/components/PointPlanSetting/positionSelection'
import pointConfig from '@/components/PointPlanSetting/pointConfig'
import { formatData, formatErrorData, formatRequest } from '@/views/business/contract/util'
import { cloneDeep } from 'lodash'

export default {
  name: 'PointPlanDetail',
  components: {
    positionSelection,
    pointConfig
  },
  data() {
    return {
      date_range: [],
      show: true,
      firstSearch: false,
      searchForm: {
        beginDate: null,
        endDate: null,
        pcaList: [], // 行政规划
        address: null, // 地址
        positionRadius: 1000,
        buildingList: [], // 选中的楼盘信息
        buildingRadiation: false, // 楼盘是否辐射
        buildingRadius: 1000, // 楼盘辐射距离
        prohibitIndustryId: null, // 禁投行业
        pointTypeIdList: [],
        floorList: [],
        abType: 'ALL',
        exclude_media_id_list: [],
        exclude_building_id_list: [],
        positionLocationList: []
      },
      // rules: {
      //   pointTypeIdList: [
      //     { type: 'array', required: true, message: '请至少选择一个点位类型', trigger: 'change' }
      //   ]
      // },
      saveFormRules: {
        plan_name: [
          { required: true, message: '请输入方案名称', trigger: 'blur' }
        ],
        customer_id: [
          { required: true, message: '请选择客户', trigger: 'change' }
        ]
        // plan_type: [
        //   { required: true, message: '请选择方案', trigger: 'change' }
        // ]
      },
      // adcodes: [],
      // point_type_arr: [],
      // no_voting_industry_arr: [],
      // floorList: [],
      // addressListParams: {
      //   page: 1,
      //   page_size: 10,
      //   boundary: '320400'
      // },
      // addressTotal: null,
      // addressDialogVisible: false,
      // addressTableData: [],
      // addressTableLoading: false,
      // chooseAddressTableData: [],
      // addressDataList: [],
      buildingArr: [],
      // // 规则过滤
      // rule_filter: {
      //   open_residential_quarters: false, // 是否开启小区过滤
      //   residential_quarters_num: 1, // 小区过滤数
      //   open_floor: false, // 是否开启楼层过滤
      //   open_market: false, // 是否开启综合市场过滤
      //   market_num: 1 // 市场过滤数字
      // },
      tmpSelectPointArr: [],
      // 选择的点位信息
      selectPointArr: [],
      buildingTableData: [], // 楼盘数据
      pointSelectionDialogVisible: false, // 选点弹窗
      pointDialogData: {
        isAllSelect: false,
        id: null,
        point_type_id: null, // 点位类型
        point_count: null, // 可选总数
        point_type_count: null, // 总数
        point_checked_count: null, // 已选择数量
        mediaPointData: null, // 点位数据
        selectAllArr: []
      },
      intentionSchemeSave: {
        id: null,
        choose_id: null,
        plan_name: null, // 方案名称
        plan_type: null, // 方案类型
        customer_id: null, // 客户ID
        memo: null, // 备注
        dataList: [], // 配置项
        tmpDataList: [], // 前端展现数据使用的配置项
        related_type: 1, // 1 合同 2 销售单
        related_id: null,
        hasBillSale: false,
        exclude_sale_choose_id: null,
        type: 1
      },
      // programmeDialogVisible: false,
      // programmeSelectPointDialogVisible: false,
      // programmePointData: {
      //   id: null, // 楼盘ID
      //   index: 0,
      //   isAllSelect: false,
      //   point_type_id: null, // 点位类型
      //   point_count: null, // 可选总数
      //   point_type_count: null, // 总数
      //   point_checked_count: null, // 已选择数量
      //   mediaPointData: null, // 点位数据
      //   selectArr: []// 点位ID集合
      // },
      centerDialogVisible: false,
      plan_type_arr: [],
      customer_arr: [],
      savePlanDialogVisible: false,
      positionSelectionDialogVisible: false,
      addConfigDialogVisible: false,
      exclusion_point_arr: [], // 排斥的点位id
      exclusion_config_arr: [], // 排斥的配置项数据索引
      tmpIndex: -1,
      errorDrawerShow: false,
      errorData: null,
      pointTypeArr: [],
      edit: false,
      type: 1,
      disabled: false,
      history_data: [],
      tmpKeys: [],
      orderTableData: [],
      tmpPointList: [],
      showPointListDialogVisible: false,
      selectOrderDialogVisible: false,
      orderId: null,
      configIndex: null,
      conflictDialogVisible: false,
      orderPointArr: [], // 需要关联的工单点位数组
      configPointArr: [], // 需要关联的配置项点位数组
      forcePointArr: [], // 冲突点位数组
      customer_id_select_disabled: false,
      billSaleStatus: 0
    }
  },
  computed: {
    // 点位选择框是否包含电梯智能框类型
    containBuildingId() {
      return this.searchForm.pointTypeIdList.find(item => item == 1) != undefined
    },
    // 点位选择框是否包含综合市场类型
    containComprehensiveMarketId() {
      return this.searchForm.pointTypeIdList.find(item => item == 9) != undefined
    },
    // 配置的点位
    configArr() {
      const tmp = []
      for (let i = 0; i < this.intentionSchemeSave.tmpDataList.length; i++) {
        tmp.push({
          index: i,
          label: this.intentionSchemeSave.tmpDataList[i].date[0] + '~' + this.intentionSchemeSave.tmpDataList[i].date[1]
        })
      }
      return tmp
    }
  },
  watch: {
    buildingTableData: {
      handler(newVal, oldVal) { // 当数据改变计算实际选中总数和未分配数
        this.clearActualNum()
        for (let i = 0; i < newVal.length; i++) {
          const tmp = newVal[i].pointTypeCountVOMap
          for (const tmpKey in tmp) {
            var count = 0
            for (let j = 0; j < tmp[tmpKey].mediaPointList.length; j++) {
              if (tmp[tmpKey].mediaPointList[j].checked) {
                count++
              }
            }
            tmp[tmpKey].to = count
            for (let j = 0; j < this.selectPointArr.length; j++) {
              if (tmpKey == this.selectPointArr[j].id) {
                this.selectPointArr[j].actual_num += count
                // this.selectPointArr[j].unassignedNum = this.selectPointArr[j].num - this.selectPointArr[j].actual_num
              }
            }
          }
        }
      },
      deep: true
    },
    selectPointArr: {
      handler(val) {
        val.forEach(item => item.unassignedNum = item.num - item.actual_num)
      },
      deep: true
    }
  },
  created() {
    const params = this.$route.params
    if (params.type !== undefined && params.type) {
      this.intentionSchemeSave.type = params.type
    }
    if (params.building_ids) {
      this.searchForm.buildingList = params.building_ids
    }
    if (params.related_id !== undefined && params.related_type !== undefined) {
      this.intentionSchemeSave.related_id = params.related_id
      this.intentionSchemeSave.related_type = params.related_type
      if (params.choose_id) {
        this.intentionSchemeSave.exclude_sale_choose_id = params.choose_id
      }
    }
    if (params.intention_scheme_id !== undefined){
      this.intentionSchemeSave.intention_scheme_id = params.intention_scheme_id
    }
    if ((params.daterange == null || params.daterange == undefined || params.daterange.length == undefined) && params.id == undefined) {
      setTimeout(() => {
        this.closeThisPage()
      }, 100)
    } else if (params.related_type === 2) { // 如果是变更
      const loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      planDetail({ id: this.intentionSchemeSave.intention_scheme_id }).then(res => {
        this.history_data = formatData(res)
        this.intentionSchemeSave.tmpDataList = cloneDeep(this.history_data)
        this.intentionSchemeSave.tmpDataList[0].date[0] = params.daterange[0]
        this.intentionSchemeSave.tmpDataList[0].date[1] = params.daterange[1]
        loading.close()
      }).catch(() => {
        loading.close()
      })
      // // 加载合同配置项
      // saleOrderDetail({ id: this.intentionSchemeSave.related_id }).then(res => {
      //   this.history_data = formatData(res)
      //   this.intentionSchemeSave.tmpDataList = cloneDeep(this.history_data)
      //   this.intentionSchemeSave.tmpDataList[0].date[0] = params.daterange[0]
      //   this.intentionSchemeSave.tmpDataList[0].date[1] = params.daterange[1]
      //   loading.close()
      // }).catch(() => {
      //   loading.close()
      // })
      this.date_range = params.daterange
      this.searchForm.beginDate = params.daterange[0]
      this.searchForm.endDate = params.daterange[1]
    } else if (params.daterange != null && params.daterange != undefined && params.daterange.length != undefined) {
      this.date_range = params.daterange
      this.searchForm.beginDate = params.daterange[0]
      this.searchForm.endDate = params.daterange[1]
      setTimeout(() => {
        this.positionSelectionDialogVisible = true
      }, 500)
    } else {
      this.date_range = [this.getDateStr(new Date()), this.getDateStr(new Date())]
      const loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.edit = true
      detail({ id: params.id }).then(res => {
        this.intentionSchemeSave.id = res.data.id
        this.intentionSchemeSave.choose_id = res.data.choose_id
        this.intentionSchemeSave.customer_id = res.data.customer_id
        this.intentionSchemeSave.memo = res.data.memo
        this.intentionSchemeSave.plan_type = res.data.plan_type ? res.data.plan_type : null
        this.intentionSchemeSave.related_type = res.data.related_type
        this.intentionSchemeSave.related_id = res.data.related_id
        this.intentionSchemeSave.plan_name = res.data.plan_name
        this.intentionSchemeSave.hasBillSale = res.data.hasBillSale
        this.intentionSchemeSave.type = res.data.type
        // 格式化后端的结构
        this.intentionSchemeSave.tmpDataList = formatData(res)
				if(res.data.type == 1 && res.data.mode == 0 && res.data.process_status == 2){
					this.intentionSchemeSave.exclude_sale_choose_id = res.data.choose_id || null;
				}
        loading.close()
      }).catch(() => {
        loading.close()
      })
    }
    if (params.customer_id) {
      if (params.related_type === 2) {
        this.customer_id_select_disabled = true
      }
      this.intentionSchemeSave.customer_id = params.customer_id
    }
    if (params.billSaleStatus) {
      this.billSaleStatus = params.billSaleStatus
    }
    this.initNoVotingIndustry()
    this.initPointType()
    this.initAdCode()
    this.initBuildingArr()
    this.initFloorList()
    this.initPlanTypeArr()
    this.initCustomerArr()
  },
  methods: {
    search() {
      if (this.searchForm.pointTypeIdList == null || this.searchForm.pointTypeIdList.length == undefined || this.searchForm.pointTypeIdList.length == 0) {
        this.$message.error('请至少选择一种点位类型')
      } else {
        this.show = !this.show
        this.firstSearch = true
        // this.tmpSelectTypeArr = this.searchForm.pointTypeIdList.map(item => {return item})
        this.rule_filter = {
          open_residential_quarters: false, // 是否开启小区过滤
          residential_quarters_num: 1, // 小区过滤数
          open_floor: false, // 是否开启楼层过滤
          open_market: false, // 是否开启综合市场过滤
          market_num: 1 // 市场过滤数字
        }
        const loading = this.$loading({
          lock: true,
          text: '加载中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        search(this.searchForm).then(
          res => {
            this.selectPointArr = []
            for (let i = 0; i < this.tmpSelectPointArr.length; i++) {
              var tmp = this.tmpSelectPointArr[i]
              this.selectPointArr.push(Object.assign({}, tmp))
            }
            this.buildingTableData = res.data
            // 遍历数据增加属性
            for (let i = 0; i < this.buildingTableData.length; i++) {
              var tmp = this.buildingTableData[i].pointTypeCountVOMap
              for (const tmpKey in tmp) {
                this.$set(tmp[tmpKey], 'to', 0)// 添加已选择数
                this.$set(tmp[tmpKey], 'canSelectNum', 0)// 添加能选择数
                this.$set(tmp[tmpKey], 'allCanSelectNum', tmp[tmpKey].point_type_count) // 添加总选择数
                for (let j = 0; j < tmp[tmpKey].mediaPointList.length; j++) {
                  this.$set(tmp[tmpKey].mediaPointList[j], 'checked', false)
                }
              }
            }
            this.formatPointDistribution()
            loading.close()
          }
        ).catch(() => {
          loading.close()
        })
      }
    },
    /**
     * 初始化禁投信息
     */
    initNoVotingIndustry() {
      list_all3rd_bycode({ code: 'khxg-hy' }).then(
        res => {
          this.no_voting_industry_arr = res.data
        }
      )
    },
    /**
     * 初始化点位类型数据
     */
    initPointType() {
      list_media_types().then(
        res => {
          this.point_type_arr = res.data
        }
      )
    },
    /**
     * 初始化行政规划
     */
    initAdCode() {
      area_list({ pid: '320400' }).then(
        res => {
          this.adcodes = res.data
        }
      )
    },
    /**
     * 初始化客户信息
     */
    initCustomerArr() {
      company_list_all({}).then(res => {
        this.customer_arr = res.data
      })
    },
    /**
     * 初始化方案类型
     */
    initPlanTypeArr() {
      list_all3rd_bycode({ code: 'xwfa-lx' }).then(
        res => {
          this.plan_type_arr = res.data
        }
      )
    },
    /**
     * 初始化楼盘下拉列表
     */
    initBuildingArr() {
      list_all({ ad_code: this.searchForm.pcaList }).then(res => {
        this.buildingArr = res.data.map(item => {
          return {
            id: item.id,
            name: item.name,
            lat: item.lat,
            lng: item.lng
          }
        })
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.searchForm.positionLocationList = []
    },
    /**
     * 获取位置信息
     */
    getLocation() {
      if (this.searchForm.address) {
        this.getAddressList()
      } else {
        this.$message.error('请输入地址')
      }
    },
    getAddressList() {
      const params = Object.assign({ keyword: this.searchForm.address }, this.addressListParams)
      this.addressTableLoading = true
      search_address_by_page(params).then(
        res => {
          this.addressTableData = res.data.data
          this.addressTableLoading = false
          this.addressTotal = res.data.count
        }
      )
      this.addressDialogVisible = true
    },
    handleCurrentChange(val) {
      this.addressListParams.page = val
      this.getAddressList()
    },
    selectAddress(row) {
      this.chooseAddressTableData.push(Object.assign({}, row))
    },
    removeAddress(index) {
      this.chooseAddressTableData.splice(index, 1)
    },
    // 点击地址搜索确认按钮
    determine() {
      const tmp = []
      for (let j = 0; j < this.chooseAddressTableData.length; j++) {
        if (this.searchForm.positionLocationList.find(item => item.id == this.chooseAddressTableData[j].id) == undefined) {
          tmp.push({
            id: this.chooseAddressTableData[j].id,
            lat: this.chooseAddressTableData[j].location.lat,
            lng: this.chooseAddressTableData[j].location.lng,
            title: this.chooseAddressTableData[j].title
          })
        }
      }
      this.searchForm.positionLocationList = this.searchForm.positionLocationList.concat(tmp)
      this.addressDialogVisible = false
    },
    closeAddressDialog() {
      this.chooseAddressTableData = []
      this.addressListParams.page = 1
      this.addressTotal = null
    },
    handleClose(index) {
      this.searchForm.positionLocationList.splice(index, 1)
    },
    pointTypeChange(val) {
      if (val.find(item => item == 1) == undefined) {
        this.searchForm.floorList = []
      }
      if (val.find(item => item == 9) == undefined) {
        this.searchForm.abType = 'ALL'
      }
      this.tmpSelectPointArr = []
      if (val != null && val.length > 0) {
        for (let i = 0; i < val.length; i++) {
          const tmp = this.point_type_arr.find(item => item.id == val[i])
          this.tmpSelectPointArr.push(
            {
              id: tmp.id, // 点位类型ID
              name: tmp.name, // 点位类型名称
              count: 0, // 点位可选总数
              num: 0, // 点位分配总数
              unassignedNum: 0, // 点位未分配数
              actual_num: 0 // 实际分配数
            }
          )
        }
      }
    },
    /**
     * 初始化楼层数据
     */
    initFloorList() {
      list_floor_selections().then(
        res => {
          this.floorList = res.data
        }
      )
    },
    removeTable(index) {
      this.$confirm('确认删除该楼盘', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        for (let i = 0; i < this.selectPointArr.length; i++) {
          this.selectPointArr[i].count -= this.buildingTableData[index].pointTypeCountVOMap[this.selectPointArr[i].id].allCanSelectNum
        }
        this.buildingTableData.splice(index, 1)
      }).catch(() => {

      })
    },
    /**
     * 获取点位类型名称
     * @param id
     * @returns {string|*}
     */
    getPointTypeName(id) {
      const tmp = this.point_type_arr.find(item => item.id == id)
      if (tmp) {
        return tmp.name
      } else {
        return ''
      }
    },
    /**
     * 格式化分配数
     */
    formatPointDistribution() {
      for (let i = 0; i < this.buildingTableData.length; i++) {
        const item = this.buildingTableData[i].pointTypeCountVOMap
        for (let j = 0; j < this.selectPointArr.length; j++) {
          this.selectPointArr[j].count += item[this.selectPointArr[j].id].point_type_count
        }
      }
    },
    /**
     * 点位数量求和
     */
    pointSum(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        } else if (index > 2 && index != columns.length - 1) {
          sums[index] = 0
          let s1 = 0
          let s2 = 0
          for (let j = 0; j < data.length; j++) {
            s1 += data[j].pointTypeCountVOMap[this.selectPointArr[index - 3].id].to
            s2 += data[j].pointTypeCountVOMap[this.selectPointArr[index - 3].id].allCanSelectNum
          }
          if (s1 != 0) {
            sums[index] = s1 + '/' + s2
          } else {
            sums[index] = s1
          }
        }
      })
      return sums
    },
    /**
     * 开启规则过滤
     */
    openRuleFilter() {
      this.selectPointArr.forEach(item => {
        item.num = 0
        item.unassignedNum = 0
        item.actual_num = 0
      }) // 清空所有分配数、未分配数、实际分配数
      this.buildingTableData.forEach(item => {
        for (const itemKey in item.pointTypeCountVOMap) {
          item.pointTypeCountVOMap[itemKey].to = 0
          item.pointTypeCountVOMap[itemKey].mediaPointList.forEach(tmp => {
            tmp.checked = false
          })
        }
      })
    },
    /**
     * 开启楼层过滤
     */
    openFloor(val) {
      this.openRuleFilter()
      this.elevatorIntelligentFrameFilter(this.rule_filter.open_residential_quarters, this.rule_filter.residential_quarters_num, val)
    },
    /**
     * 单元输入框改变事件
     */
    utilInputChange(val) {
      this.openRuleFilter()
      this.elevatorIntelligentFrameFilter(this.rule_filter.open_residential_quarters, val, this.rule_filter.open_floor)
    },
    /**
     * 开启单元过滤
     */
    openUtil(val) {
      this.openRuleFilter()
      this.elevatorIntelligentFrameFilter(val, this.rule_filter.residential_quarters_num, this.rule_filter.open_floor)
    },
    elevatorIntelligentFrameFilter(utilOpen, utilNum, floorOpen) {
      const typeId = 1
      let all = 0
      if (utilOpen && floorOpen) {
        for (let i = 0; i < this.buildingTableData.length; i++) {
          const map = new Map()
          const tmp = this.buildingTableData[i].pointTypeCountVOMap[typeId]
          tmp.mediaPointList.forEach(item => {
            const key = (item.building_number != null ? item.building_number + '号楼' : '') + (item.unit_number != null ? item.unit_number + '单元' : '')
            const key2 = (item.floor != null ? item.floor + '层' : '')
            if (map.has(key) && map.get(key).size < utilNum) {
              if (!(map.get(key).has(key2))) {
                map.get(key).set(key2, 1)
              }
            } else {
              map.set(key, new Map())
              map.get(key).set(key2, 1)
            }
          })
          tmp.allCanSelectNum = 0
          map.forEach(function(val, key) {
            tmp.allCanSelectNum += val.size
          })
          all += tmp.allCanSelectNum
        }
      } else if (floorOpen) {
        for (let i = 0; i < this.buildingTableData.length; i++) {
          const map = new Map()
          const tmp = this.buildingTableData[i].pointTypeCountVOMap[typeId]
          tmp.mediaPointList.forEach(item => {
            const key = (item.building_number != null ? item.building_number + '号楼' : '') + (item.unit_number != null ? item.unit_number + '单元' : '') + (item.floor != null ? item.floor + '层' : '')
            if (!map.has(key)) {
              map.set(key, 1)
            }
          })
          tmp.allCanSelectNum = map.size
          all += tmp.allCanSelectNum
        }
      } else if (utilOpen) {
        for (let i = 0; i < this.buildingTableData.length; i++) {
          const map = new Map()
          const tmp = this.buildingTableData[i].pointTypeCountVOMap[typeId]
          tmp.mediaPointList.forEach(item => {
            const key = (item.building_number != null ? item.building_number + '号楼' : '') + (item.unit_number != null ? item.unit_number + '单元' : '')
            if (map.has(key)) {
              if (map.get(key) < utilNum) {
                map.set(key, map.get(key) + 1)
              }
            } else {
              map.set(key, 1)
            }
          })
          tmp.allCanSelectNum = 0
          map.forEach(function(val, key) {
            tmp.allCanSelectNum += val
          })
          all += tmp.allCanSelectNum
        }
      } else {
        for (let i = 0; i < this.buildingTableData.length; i++) {
          const tmp = this.buildingTableData[i].pointTypeCountVOMap[typeId]
          tmp.allCanSelectNum = tmp.point_type_count
          all += tmp.point_type_count
        }
      }
      this.selectPointArr.forEach(item => {
        if (item.id == typeId) {
          item.count = all
        }
      })
    },
    /**
     * 开启综合市场过滤
     */
    openMarket(val) {
      const typeId = 9
      this.openRuleFilter()
      if (val) {
        this.marketOpenFilter(typeId, this.rule_filter.market_num)
      } else {
        this.marketCloseFilter(typeId)
      }
    },
    /**
     * 综合市场输入框事件
     */
    marketInputChange(val) {
      const typeId = 9
      this.openRuleFilter()
      if (this.rule_filter.open_market) {
        this.marketOpenFilter(typeId, val)
      }
    },
    /**
     * 综合市场过滤
     * @param typeId
     * @param num
     */
    marketOpenFilter(typeId, num) {
      let all = 0
      for (let i = 0; i < this.buildingTableData.length; i++) {
        const tmp = this.buildingTableData[i].pointTypeCountVOMap[typeId]
        let total = 0
        total += tmp.mediaPointList.length > num ? num : tmp.mediaPointList.length
        tmp.allCanSelectNum = total
        all += total
      }
      this.selectPointArr.forEach(item => {
        if (item.id == typeId) {
          item.count = all
        }
      })
    },
    marketCloseFilter(typeId) {
      let all = 0
      for (let i = 0; i < this.buildingTableData.length; i++) {
        const tmp = this.buildingTableData[i].pointTypeCountVOMap[typeId]
        tmp.allCanSelectNum = tmp.point_type_count
        all += tmp.point_type_count
      }
      this.selectPointArr.forEach(item => {
        if (item.id == typeId) {
          item.count = all
        }
      })
    },
    /**
     * 表格输入框change事件 需要改变点位选中状态
     * @param row
     * @param num
     * @param pointTypeId
     */
    tableInputChange(row, num, pointTypeId) {
      if (num <= 0) {
        var data = row.pointTypeCountVOMap[pointTypeId].mediaPointList
        for (let i = data.length - 1; i >= 0; i--) {
          if (data[i].checked && num != 0) {
            num++
            data[i].checked = !data[i].checked
          }
        }
      }
      var data = row.pointTypeCountVOMap[pointTypeId].mediaPointList
      var newData = {}
      // 如果是电梯智能框 格式化数据
      if (pointTypeId == 1 && (this.rule_filter.open_floor || this.rule_filter.open_residential_quarters)) {
        if (this.rule_filter.open_floor && this.rule_filter.open_residential_quarters) {
          for (let i = 0; i < data.length; i++) {
            var temp = data[i]
            const key = (temp.building_number != null ? temp.building_number + '号楼' : '') + (temp.unit_number != null ? temp.unit_number + '单元' : '')
            if (!(key in newData)) {
              this.$set(newData, key, {})
            }
            const key2 = (temp.floor != null ? temp.floor + '层' : '')
            if (!(key2 in newData[key])) {
              this.$set(newData[key], key2, [])
            }
            newData[key][key2].push(temp)
          }
        } else if (this.rule_filter.open_residential_quarters) {
          for (let i = 0; i < data.length; i++) {
            var temp = data[i]
            const key = (temp.building_number != null ? temp.building_number + '号楼' : '') + (temp.unit_number != null ? temp.unit_number + '单元' : '')
            if (!(key in newData)) {
              this.$set(newData, key, [])
            }
            newData[key].push(temp)
          }
        } else if (this.rule_filter.open_floor) {
          for (let i = 0; i < data.length; i++) {
            var temp = data[i]
            const key = (temp.building_number != null ? temp.building_number + '号楼' : '') + (temp.unit_number != null ? temp.unit_number + '单元' : '') + (temp.floor != null ? temp.floor + '层' : '')
            if (!(key in newData)) {
              this.$set(newData, key, [])
            }
            newData[key].push(temp)
          }
        }
      } else {
        newData = []
        data.forEach(item => {
          newData.push(item)
        })
      }
      this.autoSelectPoint(newData, num, pointTypeId)
    },
    /**
     * 自动选位
     * @param newData
     * @param num
     */
    autoSelectPoint(newData, num, pointId) {
      if (Array.isArray(newData)) {
        newData.forEach(item => {
          if (num != 0 && !(item.checked)) {
            if (this.itemChange(pointId, item, newData, null, true)) {
              num--
            }
          }
        })
      } else {
        for (const key in newData) {
          if (Array.isArray(newData[key])) {
            newData[key].forEach(item => {
              if (num != 0 && !(item.checked)) {
                if (this.itemChange(pointId, item, newData[key], null, true)) {
                  num--
                }
              }
            })
          } else {
            for (const key2 in newData[key]) {
              newData[key][key2].forEach(item => {
                if (num != 0 && !(item.checked)) {
                  if (this.itemChange(pointId, item, newData[key], null, true)) {
                    num--
                  }
                }
              })
            }
          }
        }
      }
    },
    /**
     * 取消全选
     * @param newData
     */
    cancelALlPoint(newData, pointId) {
      if (Array.isArray(newData)) {
        newData.forEach(item => {
          if (item.checked) {
            this.itemChange(pointId, item, newData, null, true)
          }
        })
      } else {
        for (const key in newData) {
          if (Array.isArray(newData[key])) {
            newData[key].forEach(item => {
              if (item.checked) {
                this.itemChange(pointId, item, newData, null, true)
              }
            })
          } else {
            for (const key2 in newData[key]) {
              newData[key][key2].forEach(item => {
                if (item.checked) {
                  this.itemChange(pointId, item, newData[key][key2], newData[key], true)
                }
              })
            }
          }
        }
      }
    },
    /**
     * 全选按钮点击事件
     * @param val
     * @param data
     * @param num
     */
    allSelectCheckBox(val, data, num, pointId) {
      if (val) {
        this.autoSelectPoint(data, num, pointId)
      } else {
        this.cancelALlPoint(data, pointId)
      }
    },
    /**
     * 点位分配输入框change事件 需要改变点位选中状态
     * @param val
     * @param pointTypeId
     * @param item
     */
    pointAllocationInputChange(val, pointTypeId, item) {
      const map = this.buildingDistribution(pointTypeId, val)
      for (let i = 0; i < this.buildingTableData.length; i++) {
        if (map.has(this.buildingTableData[i].id)) {
          const obj = map.get(this.buildingTableData[i].id)
          this.tableInputChange(this.buildingTableData[i], obj.distributionNum, pointTypeId)
        }
      }
    },
    // 清楚所有实际选中数
    clearActualNum() {
      this.selectPointArr.forEach(item => item.actual_num = 0)
    },
    // 计算每个楼盘平均分配数
    buildingDistribution(pointTypeId, num) {
      let actualDistributionNum = num
      let surplusNum = 0
      const map = new Map()
      for (let i = 0; i < this.buildingTableData.length; i++) {
        var tmp = this.buildingTableData[i].pointTypeCountVOMap[pointTypeId]
        if (tmp.to > 0) {
          actualDistributionNum -= tmp.to
        }
        if (tmp.allCanSelectNum - tmp.to > 0) {
          surplusNum += (tmp.allCanSelectNum - tmp.to)
          map.set(this.buildingTableData[i].id, {
            allNum: tmp.allCanSelectNum - tmp.to, // 总共可分配数
            distributionNum: 0, // 应该分配数
            alreadyDistributionNum: tmp.to // 已经分配数
          })
        }
      }
      // 循环计算每个楼盘的分配数
      while (actualDistributionNum > 0 && surplusNum > 0) {
        map.forEach(function(value, key) {
          if (actualDistributionNum > 0) {
            if (value.alreadyDistributionNum > 0) {
              value.alreadyDistributionNum -= 1
            } else if (value.allNum > 0) {
              value.distributionNum += 1
              value.allNum -= 1
              actualDistributionNum--
              surplusNum--
            }
          }
        })
      }
      return map
    },
    // 关闭选点弹窗
    closePointSelectionDialog() {
    },
    // 显示精准选点弹窗
    showPointDetail(data, id, typeId) {
      this.pointDialogData.isAllSelect = false
      this.pointDialogData.id = id
      this.pointDialogData.point_type_id = data.point_type_id
      this.pointDialogData.point_checked_count = data.to
      this.pointDialogData.point_type_count = data.point_type_count
      this.pointDialogData.point_count = data.allCanSelectNum
      this.pointDialogData.selectAllArr = []
      // 如果是电梯智能框 格式化数据
      if (typeId == 1 && (this.rule_filter.open_floor || this.rule_filter.open_residential_quarters)) {
        if (this.rule_filter.open_floor && this.rule_filter.open_residential_quarters) {
          this.pointDialogData.mediaPointData = {}
          for (let i = 0; i < data.mediaPointList.length; i++) {
            var temp = data.mediaPointList[i]
            const key = (temp.building_number != null ? temp.building_number + '号楼' : '') + (temp.unit_number != null ? temp.unit_number + '单元' : '')
            if (!(key in this.pointDialogData.mediaPointData)) {
              this.$set(this.pointDialogData.mediaPointData, key, {})
            }
            const key2 = (temp.floor != null ? temp.floor + '层' : '')
            if (!(key2 in this.pointDialogData.mediaPointData[key])) {
              this.$set(this.pointDialogData.mediaPointData[key], key2, [])
            }
            this.pointDialogData.mediaPointData[key][key2].push(Object.assign({}, temp))
            if (temp.checked) {
              this.pointDialogData.selectAllArr.push(temp.id)
            }
          }
        } else if (this.rule_filter.open_residential_quarters) {
          this.pointDialogData.mediaPointData = {}
          for (let i = 0; i < data.mediaPointList.length; i++) {
            var temp = data.mediaPointList[i]
            const key = (temp.building_number != null ? temp.building_number + '号楼' : '') + (temp.unit_number != null ? temp.unit_number + '单元' : '')
            if (!(key in this.pointDialogData.mediaPointData)) {
              this.$set(this.pointDialogData.mediaPointData, key, [])
            }
            this.pointDialogData.mediaPointData[key].push(Object.assign({}, temp))
            if (temp.checked) {
              this.pointDialogData.selectAllArr.push(temp.id)
            }
          }
        } else if (this.rule_filter.open_floor) {
          this.pointDialogData.mediaPointData = {}
          for (let i = 0; i < data.mediaPointList.length; i++) {
            var temp = data.mediaPointList[i]
            const key = (temp.building_number != null ? temp.building_number + '号楼' : '') + (temp.unit_number != null ? temp.unit_number + '单元' : '') + (temp.floor != null ? temp.floor + '层' : '')
            if (!(key in this.pointDialogData.mediaPointData)) {
              this.$set(this.pointDialogData.mediaPointData, key, [])
            }
            this.pointDialogData.mediaPointData[key].push(Object.assign({}, temp))
            if (temp.checked) {
              this.pointDialogData.selectAllArr.push(temp.id)
            }
          }
        }
      } else {
        this.pointDialogData.mediaPointData = []
        data.mediaPointList.forEach(item => {
          this.pointDialogData.mediaPointData.push(Object.assign({}, item))
          if (item.checked) {
            this.pointDialogData.selectAllArr.push(item.id)
          }
        })
      }
      this.pointSelectionDialogVisible = true
    },
    /**
     * 点位点击事件
     * @param item 点击的点位信息
     * @param arr 点击点位所在的数据信息
     * @param utilArr 当同时开启楼层和单元过滤的单元点位信息
     */
    itemChange(pointId, item, arr, utilArr, type = false) {
      let flag = false
      // 如果是电梯智能框并开启了规则过滤
      if (pointId == 1 && (this.rule_filter.open_floor || this.rule_filter.open_residential_quarters)) {
        let total = this.rule_filter.residential_quarters_num
        // 同时开启
        if (this.rule_filter.open_floor && this.rule_filter.open_residential_quarters) {
          for (const key in utilArr) {
            for (let i = 0; i < utilArr[key].length; i++) {
              if (total == 0) {
                break
              }
              const tmp = utilArr[key][i]
              if (tmp.checked) {
                total--
              }
            }
          }
          let f = false
          for (let i = 0; i < arr.length; i++) {
            const tmp = arr[i]
            if (tmp.checked) {
              f = true
              break
            }
          }
          if (!(f) && total > 0) {
            flag = true
          }
        } else if (this.rule_filter.open_floor) { // 开启楼层过滤
          let f = false
          for (let i = 0; i < arr.length; i++) {
            const tmp = arr[i]
            if (tmp.checked) {
              f = true
              break
            }
          }
          if (!f) {
            flag = true
          }
        } else if (this.rule_filter.open_residential_quarters) { // 开启单元过滤
          for (let i = 0; i < arr.length; i++) {
            if (total == 0) {
              break
            }
            const tmp = arr[i]
            if (tmp.checked) {
              total--
            }
          }
          if (total > 0) {
            flag = true
          }
        }
      } else if (pointId == 9 && this.rule_filter.open_market) { // 开启综合市场过滤
        let total = this.rule_filter.market_num
        for (let i = 0; i < arr.length; i++) {
          if (total == 0) {
            break
          }
          const tmp = arr[i]
          if (tmp.checked) {
            total--
          }
        }
        if (total > 0) {
          flag = true
        }
      } else {
        flag = true
      }
      if (item.checked) {
        this.pointDialogData.point_checked_count -= 1
        item.checked = !item.checked
        this.pointDialogData.selectAllArr = this.pointDialogData.selectAllArr.filter(t => t != item.id)
        // 如果是综合市场并且开启了AB面规则
        if (pointId == 9 && this.searchForm.abType == 'AB') {
          const find = this.pointDialogData.mediaPointData.find(tmp => tmp.id == item.pair_media_id)
          if (find) {
            this.pointDialogData.point_checked_count -= 1
            find.checked = !find.checked
            this.pointDialogData.selectAllArr = this.pointDialogData.selectAllArr.filter(t => t != find.id)
          }
        }
      } else {
        if (flag) {
          this.pointDialogData.point_checked_count += 1
          item.checked = !item.checked
          this.pointDialogData.selectAllArr.push(item.id)
          if (pointId == 9 && this.searchForm.abType == 'AB') {
            const find = this.pointDialogData.mediaPointData.find(tmp => tmp.id == item.pair_media_id)
            if (find) {
              this.pointDialogData.point_checked_count += 1
              find.checked = !find.checked
              this.pointDialogData.selectAllArr.push(find.id)
            }
          }
          return true
        } else {
          if (!type) {
            this.$message.error('超出规则限制')
          }
        }
      }
    },
    pointDialogConfirm() {
      for (let i = 0; i < this.buildingTableData.length; i++) {
        if (this.buildingTableData[i].id == this.pointDialogData.id) {
          var tmp = this.buildingTableData[i].pointTypeCountVOMap[this.pointDialogData.point_type_id].mediaPointList
          for (let j = 0; j < tmp.length; j++) {
            if (this.pointDialogData.selectAllArr.find(t => t == tmp[j].id) == undefined) {
              tmp[j].checked = false
            } else {
              tmp[j].checked = true
            }
          }
        }
      }
      this.pointSelectionDialogVisible = false
    },
    // 确认按钮点击事件
    addConfig() {
      // 检查是否有未分配的点位
      if (this.check()) {
        const date = []
        this.date_range.forEach(item => {
          date.push(item)
        })
        const arr = []
        this.selectPointArr.filter(item => item.actual_num > 0).forEach(item => {
          arr.push(item.id)
        }) // 所选择的点位类型数组
        const dataArr = []
        for (let i = 0; i < this.buildingTableData.length; i++) {
          const temp = this.buildingTableData[i]
          const tmp = {}
          tmp.id = temp.id
          tmp.name = temp.name
          tmp.address = temp.address
          tmp.pointTypeCountVOMap = {}
          let flag = false
          for (let j = 0; j < arr.length; j++) {
            if (temp.pointTypeCountVOMap[arr[j]].to > 0) {
              flag = true
            }
            const tmpArr = []
            temp.pointTypeCountVOMap[arr[j]].mediaPointList.forEach(item => {
              tmpArr.push(Object.assign({}, item))
            })
            tmp.pointTypeCountVOMap[arr[j]] = Object.assign({}, temp.pointTypeCountVOMap[arr[j]])
            tmp.pointTypeCountVOMap[arr[j]].mediaPointList = tmpArr
          }
          if (flag) {
            dataArr.push(tmp)
          }
        }
        if (dataArr.length == 0) {
          this.$message({
            message: '请勿提交无效的配置',
            type: 'warning'
          })
          return
        }
        this.positionSelectionDialogVisible = false
        if (this.tmpIndex >= 0) { // 如果是合并
          const config = this.intentionSchemeSave.tmpDataList[this.tmpIndex]
          // 先合并点位类型数据
          arr.forEach(item => {
            if (config.arr.find(i => i == item) == undefined) {
              config.arr.push(item)
            }
          })
          const that = this
          // 合并点位数据
          dataArr.forEach(item => {
            const building = config.dataArr.find(i => i.id == item.id)
            if (building == undefined) {
              config.dataArr.push(Object.assign({}, item))
            } else {
              arr.forEach(tmp => {
                if (building.pointTypeCountVOMap[tmp] == undefined) {
                  that.$set(building.pointTypeCountVOMap, tmp, Object.assign({}, item.pointTypeCountVOMap[tmp]))
                } else {
                  item.pointTypeCountVOMap[tmp].mediaPointList.forEach(t => {
                    const find = building.pointTypeCountVOMap[tmp].mediaPointList.find(s => s.id == t.id)
                    if (find == undefined) {
                      building.pointTypeCountVOMap[tmp].mediaPointList.push(Object.assign({}, t))
                    } else {
                      if (t.checked) {
                        find.checked = true
                        building.pointTypeCountVOMap[tmp].to++
                      }
                    }
                  })
                }
              })
            }
          })
        } else {
          this.intentionSchemeSave.tmpDataList.push({
            dataArr,
            arr,
            date
          })
        }
      } else {
        this.$message.error('请将点位分配完')
      }
    },
    check() {
      let flag = true
      this.selectPointArr.forEach(item => {
        if (item.unassignedNum != 0) {
          flag = false
        }
      })
      return flag
    },
    // 配置项点位数量求和
    choosePointSum(param, i) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        } else if (index != columns.length - 1) {
          sums[index] = 0
          for (let j = 0; j < data.length; j++) {
            sums[index] += data[j].pointTypeCountVOMap[this.intentionSchemeSave.tmpDataList[i].arr[index - 1]] ? data[j].pointTypeCountVOMap[this.intentionSchemeSave.tmpDataList[i].arr[index - 1]].to : 0
          }
        }
      })
      return sums
    },
    // 显示所有点位
    showAllPoint(typeId, data, id, index) {
      if (data.point_type_count == 0) {
        this.$message({
          message: '无可选点位',
          type: 'warning'
        })
      } else {
        this.programmePointData.id = id
        this.programmePointData.index = index
        this.programmePointData.selectArr = []
        this.programmePointData.isAllSelect = false
        this.programmePointData.point_type_id = typeId
        this.programmePointData.point_count = data.point_type_count
        this.programmePointData.point_type_count = data.point_type_count
        this.programmePointData.point_checked_count = data.to
        this.programmePointData.mediaPointData = []
        data.mediaPointList.forEach(item => {
          if (item.checked) {
            this.programmePointData.selectArr.push(item.id)
          }
          this.programmePointData.mediaPointData.push(Object.assign({}, item))
        })
        this.programmeSelectPointDialogVisible = true
      }
    },
    allSelectCheckBoxChange(val) {
      if (val) {
        this.programmePointData.selectArr = []
        this.programmePointData.mediaPointData.forEach(item => {
          item.checked = true
          this.programmePointData.selectArr.push(item.id)
        })
        this.programmePointData.point_checked_count = this.programmePointData.point_count
      } else {
        this.programmePointData.mediaPointData.forEach(item => {
          item.checked = false
        })
        this.programmePointData.selectArr = []
        this.programmePointData.point_checked_count = 0
      }
    },
    programmeItemChange(item) {
      if (item.checked) {
        this.programmePointData.point_checked_count -= 1
        this.programmePointData.selectArr = this.programmePointData.selectArr.filter(t => t != item.id)
      } else {
        this.programmePointData.point_checked_count += 1
        this.programmePointData.selectArr.push(item.id)
      }
      item.checked = !item.checked
    },
    programmeConfirm() {
      const tmp = this.intentionSchemeSave.tmpDataList[this.programmePointData.index].dataArr
      for (let i = 0; i < tmp.length; i++) {
        if (tmp[i].id == this.programmePointData.id) {
          var temp = tmp[i].pointTypeCountVOMap[this.programmePointData.point_type_id]
          temp.to = this.programmePointData.selectArr.length
          for (let j = 0; j < temp.mediaPointList.length; j++) {
            const item = temp.mediaPointList[j]
            if (this.programmePointData.selectArr.find(t => t == item.id) != undefined) {
              item.checked = true
            } else {
              item.checked = false
            }
          }
        }
      }
      this.programmeSelectPointDialogVisible = false
    },
    chooseTableRemove(i, index) {
      this.$confirm('确认删除该楼盘', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.intentionSchemeSave.tmpDataList[i].dataArr.length == 1) {
          this.intentionSchemeSave.tmpDataList.splice(i, 1)
        } else {
          this.intentionSchemeSave.tmpDataList[i].dataArr.splice(index, 1)
        }
      }).catch(() => {

      })
    },
    /**
     * 删除配置项
     * @param index
     */
    // removeConfig(index) {
    //   this.$confirm('确认删除该配置', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(() => {
    //     this.intentionSchemeSave.tmpDataList.splice(index, 1)
    //   }).catch(() => {
    //
    //   })
    // },
    copyBuildingClick(index) {
      this.tmpIndex = index
      this.centerDialogVisible = true
    },
    copyBuilding() {
      this.$refs['searchForm'].resetFields()
      this.searchForm.exclude_building_id_list = []
      this.searchForm.exclude_media_id_list = []
      this.searchForm.buildingList = []
      this.intentionSchemeSave.tmpDataList[this.tmpIndex].dataArr.forEach(item => {
        this.searchForm.buildingList.push(Object.assign({}, this.buildingArr.find(t => t.id == item.id)))
      })
      this.selectPointArr = []
      this.searchForm.pointTypeIdList = []
      this.positionSelectionDialogVisible = true
      this.centerDialogVisible = false
      this.tmpIndex = -1
    },
    /**
     * 增加配置
     */
    addConfigClick() {
      this.addConfigDialogVisible = true
    },
    /**
     *
     */
    addBuilding(index) {
      this.tmpIndex = index
      this.$refs['searchForm'].resetFields()
      this.searchForm.exclude_building_id_list = []
      this.searchForm.exclude_media_id_list = []
      // 拉取所选点位
      this.searchForm.pointTypeIdList = []
      this.intentionSchemeSave.tmpDataList[index].arr.forEach(item => {
        this.searchForm.pointTypeIdList.push(item)
      })
      this.searchForm.exclude_building_id_list = this.intentionSchemeSave.tmpDataList[index].dataArr.map(t => {
        return t.id
      })
      this.positionSelectionDialogVisible = true
      this.pointTypeChange(this.searchForm.pointTypeIdList)
    },
    /**
     * 对增加的类型数据进行请求并存到本地
     */
    getPointData(pointTypeId, data, buildingId, index) {
      const req = {
        beginDate: this.intentionSchemeSave.tmpDataList[index].date[0],
        endDate: this.intentionSchemeSave.tmpDataList[index].date[1],
        buildingList: [{ id: buildingId }],
        pointTypeIdList: [pointTypeId],
        buildingRadiation: false,
        must_include_media_id_list: data[pointTypeId].mediaPointList.map(item => {
          if (item.checked) {
            return item.id
          }
        })
      }
      const loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      // 请求接口获取数据
      search(req).then(
        res => {
          if (res.data.length > 0) {
            if (data[pointTypeId] != undefined && data[pointTypeId].to != 0) {
              this.$set(res.data[0].pointTypeCountVOMap[pointTypeId], 'to', data[pointTypeId].to)
            } else {
              this.$set(res.data[0].pointTypeCountVOMap[pointTypeId], 'to', 0)
            }
            if (data[pointTypeId] != undefined) {
              data[pointTypeId].mediaPointList.forEach(item => {
                if (item.checked) {
                  const point = res.data[0].pointTypeCountVOMap[pointTypeId].mediaPointList.find(i => i.id == item.id)
                  if (point) {
                    point.checked = true
                  }
                }
              })
            }
            this.$set(data, pointTypeId, res.data[0].pointTypeCountVOMap[pointTypeId])
          } else {
            const tmp = {
              mediaPointList: [],
              point_type_count: 0,
              point_type_id: pointTypeId,
              to: 0
            }
            this.$set(data, pointTypeId, tmp)
          }
          this.showAllPoint(pointTypeId, data[pointTypeId], buildingId, index)
          loading.close()
        }
      ).catch(() => {
        loading.close()
      })
    },
    /**
     * 关闭配置弹框
     */
    closeConfigDialog() {
      this.buildingTableData = []
      this.selectPointArr = []
      this.searchForm = {
        beginDate: null,
        endDate: null,
        pcaList: [], // 行政规划
        address: null, // 地址
        positionRadius: 1000,
        buildingList: [], // 选中的楼盘信息
        buildingRadiation: false, // 楼盘是否辐射
        buildingRadius: 1000, // 楼盘辐射距离
        prohibitIndustryId: null, // 禁投行业
        pointTypeIdList: [],
        floorList: [],
        abType: 'ALL',
        exclude_media_id_list: [],
        exclude_building_id_list: [],
        positionLocationList: []
      }
      this.show = true
      // 重置合并索引
      this.tmpIndex = -1
      this.firstSearch = false
    },
    save(flag) {
      this.$refs['saveForm'].validate((valid) => {
        if (valid) {
          this.intentionSchemeSave.dataList = []
          for (let i = 0; i < this.intentionSchemeSave.tmpDataList.length; i++) {
            this.intentionSchemeSave.dataList.push(
              formatRequest(this.intentionSchemeSave.tmpDataList[i], i)
            )
          }
          const p = this.checkPointSpec()
          if (p !== null) {
            let pointDetailStr = this.getPointDetailStr(p)
            this.$message({
              showClose: true,
              message: pointDetailStr,
              type: 'error',
              duration: 5000
            })
            return
          }
          if (this.intentionSchemeSave.type === 1) {
            this.savePlanDialogVisible = true
            if (flag) {
              this.intentionSchemeSave.id = null
              this.intentionSchemeSave.choose_id = null
              this.intentionSchemeSave.exclude_sale_choose_id = null
            }
          } else {
            if (flag) {
              this.intentionSchemeSave.id = null
              this.intentionSchemeSave.choose_id = null
              this.intentionSchemeSave.exclude_sale_choose_id = null
            }
            this.notLock()
          }
        }
      })
    },
    notLock() {
      const loading = this.$loading({
        lock: true,
        text: '提交中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      save(this.intentionSchemeSave).then(
        res => {
          if (res.code == 200) {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.closeThisPage()
            this.savePlanDialogVisible = false
          }
          loading.close()
        }
      ).catch(() => {
        this.savePlanDialogVisible = false
        loading.close()
      })
    },
    /**
     * 检查点位是否有价格id
     */
    checkPointSpec() {
      let p = null
      this.intentionSchemeSave.dataList.forEach(item => {
        item.pointList.forEach(point => {
          if (point.media_type_spec_price_id === null || point.media_type_spec_price_id === undefined) {
            if (p === null) {
              p = point
            }
          }
        })
      })
      return p
    },
    getPointDetailStr(p) {
      let str = ''
      let find = this.intentionSchemeSave.tmpDataList[0].dataArr.find(building => building.id === p.building_area_id)
      if (find !== undefined) {
        str += find.name + '楼盘中的'
      }
      let mediaType = this.point_type_arr.find(type => p.media_type_id === type.id)
      if (mediaType !== undefined) {
        str += mediaType.name + '类型的点位有一个编号为：' + p.code + '的点位未设置价格类型'
      }
      return str
    },
    lock() {
      const loading = this.$loading({
        lock: true,
        text: '提交中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      lock(this.intentionSchemeSave).then(
        res => {
          if (res.data.error_type == undefined) {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.savePlanDialogVisible = false
            loading.close()
            this.closeThisPage()
          } else {
            this.errorData = res.data
            this.savePlanDialogVisible = false
            formatErrorData(this.intentionSchemeSave, res.data, this.point_type_arr, this)
            this.$message.warning('点位有冲突,可点击按钮查看冲突详情')
          }
          loading.close()
        }
      ).catch(() => {
        this.savePlanDialogVisible = false
        loading.close()
      })
    },
    closeThisPage() {
      this.$store.dispatch('tagsView/closePageTo', {
        closeName: this.$route.name,
        toPath: {
          name: 'purpose_plan'
        }
      })
    },
    getDateStr(date) {
      return date.getFullYear() + '-' + ((date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : '0' + (date.getMonth() + 1)) + '-' + (date.getDate() > 9 ? date.getDate() : ('0' + date.getDate()))
    },
    closeSearchDialog() {
      this.positionSelectionDialogVisible = false
      this.date_range = []
      this.tmpIndex = -1
      this.type = -1
    },
    /**
     * 保存配置项
     * @param data
     */
    saveConfig(data) {
      const { type, arr, date, dataArr } = data
      if (this.tmpIndex >= 0) { // 如果是合并
        const config = this.intentionSchemeSave.tmpDataList[this.tmpIndex]
        // 先合并点位类型数据
        arr.forEach(item => {
          if (config.arr.find(i => i == item) == undefined) {
            config.arr.push(item)
          }
        })
        const that = this
        // 合并点位数据
        dataArr.forEach(item => {
          const building = config.dataArr.find(i => i.id == item.id)
          if (building == undefined) {
            config.dataArr.push(Object.assign({}, item))
          } else {
            // 处理点位数据
            arr.forEach(tmp => {
              if (building.pointTypeCountVOMap[tmp] == undefined) {
                that.$set(building.pointTypeCountVOMap, tmp, Object.assign({}, item.pointTypeCountVOMap[tmp]))
              } else {
                item.pointTypeCountVOMap[tmp].mediaPointList.forEach(t => {
                  const find = building.pointTypeCountVOMap[tmp].mediaPointList.find(s => s.id == t.id)
                  if (find == undefined) {
                    building.pointTypeCountVOMap[tmp].mediaPointList.push(Object.assign({}, t))
                    if (t.checked) {
                      building.pointTypeCountVOMap[tmp].to++
                    }
                  } else {
                    if (t.checked) {
                      find.checked = true
                      building.pointTypeCountVOMap[tmp].to++
                    }
                  }
                })
              }
            })
            // 处理套餐数据
            if (type == 0) {
              item.comboCountInfoList.forEach(combo => {
                const tmp_combo = building.comboCountInfoList.find(building_combo => building_combo.id == combo.id)
                combo.ruleList.forEach(rule => {
                  const tmp_rule = tmp_combo.ruleList.find(building_combo_rule => rule.rule_id == building_combo_rule.rule_id)
                  tmp_rule.count += rule.count
                })
                tmp_combo.count += combo.count
              })
            }
          }
        })
      } else {
        this.intentionSchemeSave.tmpDataList.push({
          type,
          dataArr,
          arr,
          date
        })
      }
      this.closeSearchDialog()
    },
    /**
     * 删除配置项
     * @param index
     */
    removeConfig(index) {
      this.intentionSchemeSave.tmpDataList.splice(index, 1)
    },
    /**
     * 删除配置项中的楼盘
     * @param i
     * @param index
     */
    removeConfigBuilding(i, index) {
      if (this.intentionSchemeSave.tmpDataList[i].dataArr.length == 1) {
        this.intentionSchemeSave.tmpDataList.splice(i, 1)
      } else {
        this.intentionSchemeSave.tmpDataList[i].dataArr.splice(index, 1)
      }
    },
    /**
     * 配置项中的楼盘数据
     * @param configIndex
     * @param buildingId
     * @param isConflict 是否是冲突
     * @param pointTypeId
     * @param mediaArr
     */
    editConfigBuildingData(configIndex, buildingId, pointTypeId, mediaArr, isConflict = false) {
      debugger
      if (isConflict) {
        this.intentionSchemeSave.tmpDataList[configIndex].dataArr.forEach(item => {
          if (item.id == buildingId) {
            mediaArr.forEach(tmp => {
              const find = item.pointTypeCountVOMap[pointTypeId].mediaPointList.find(point => point.id == tmp.id)
              if (find) {
                item.pointTypeCountVOMap[pointTypeId].to--
                find.checked = false
              }
            })
          }
        })
      } else {
        this.intentionSchemeSave.tmpDataList[configIndex].dataArr.forEach(item => {
          if (item.id == buildingId) {
            mediaArr.forEach(tmp => {
              const find = item.pointTypeCountVOMap[pointTypeId].mediaPointList.find(point => point.id == tmp.id)
              if (find) {
                if (find.checked != tmp.checked) {
                  if (tmp.checked) {
                    item.pointTypeCountVOMap[pointTypeId].to++
                  } else {
                    find.work_order_id = null
                    find.relation_point.is_relation = false
                    find.relation_point.relation_point = null
                    item.pointTypeCountVOMap[pointTypeId].to--
                  }
                  find.checked = tmp.checked
                }
              } else {
                item.pointTypeCountVOMap[pointTypeId].push(Object.assign({}, find))
              }
            })
          }
        })
      }
    },
    /**
     * 获取搜索默认配置项
     * @param index
     * @param type 1:增加排斥点位 2:增加排斥楼盘 3:复用楼盘
     * @param date 时间
     * @param arr 数据（排斥的点位数据或排斥的楼盘或复用的楼盘）
     * @param pointTypeArr 选中的点位类型数据
     * @param configType 配置项的类型
     * @param disabled 增加的配置是否可以换类型
     */
    getSearchConfig(index, type, date, arr, pointTypeArr, configType, disabled) {
      this.tmpIndex = index
      if (type == 1) {
        this.searchForm.exclude_media_id_list = arr
      } else if (type == 2) {
        this.searchForm.exclude_building_id_list = arr
      } else {
        this.searchForm.buildingList = arr
      }
      this.date_range = date
      this.searchForm.pointTypeIdList = pointTypeArr
      this.type = configType
      this.disabled = disabled
      this.positionSelectionDialogVisible = true
    },
    editBuildingIdList(arr) {
      this.searchForm.buildingList = arr
    },
    editPointTypeIdList(arr) {
      this.searchForm.pointTypeIdList = arr
    },
    showPointList(arr) {
      this.tmpPointList = arr
      this.showPointListDialogVisible = true
    },
    showSelectOrderDialog(index) {
      this.configIndex = index
      this.selectOrderDialogVisible = true
    },
    /**
     * 关联工单方法
     */
    relationWorkOrder() {
      let configPointArr = []
      // 获取配置项所有点位
      this.intentionSchemeSave.tmpDataList[this.configIndex].dataArr.forEach(building => {
        for (let key in building.pointTypeCountVOMap) {
          configPointArr = configPointArr.concat(building.pointTypeCountVOMap[key].mediaPointList.filter(point => point.checked))
        }
      })
      let orderPointArr = []
      // 获取工单所有点位
      let find = this.orderTableData.find(order => order.worker_order_id == this.orderId)
      if (find) {
        for (const key in find.items) {
          orderPointArr = orderPointArr.concat(find.items[key].mediaPointList)
        }
      }
      // 1 检查点位是否与配置项有冲突
      let forcePointArr = this.checkPointConflict(configPointArr, orderPointArr)
      if (forcePointArr.length > 0) {
        // 2 没有冲突直接关联 有冲突要么抢点位要么关联剩下的点位
        this.configPointArr = configPointArr
        this.orderPointArr = orderPointArr
        this.forcePointArr = forcePointArr
        this.conflictDialogVisible = true
      } else {
        this.relationPoint(orderPointArr, configPointArr, false, [])
        this.selectOrderDialogVisible = false
      }
    },
    /**
     * 检查点位冲突 返回冲突的点位数组
     * @param configPointArr
     * @param orderPointArr
     * @returns {arr}
     */
    checkPointConflict(configPointArr, orderPointArr) {
      let arr = []
      // 遍历检查
      for (let i = 0; i < configPointArr.length; i++) {
        let item = configPointArr[i]
        let find = orderPointArr.find(point => point.id == item.id)
        if (find && find.is_relation && find.relation_config_index != this.configIndex) {
          arr.push(find)
        }
      }
      return arr
    },
    /**
     * 关联点位
     * @param orderPointArr    工单点位
     * @param configPointArr   配置项点位
     * @param forceRelation 是否强制关联
     * @param forcePointArr 强制关联的点位
     */
    relationPoint(orderPointArr, configPointArr, forceRelation, forcePointArr) {
      if (forceRelation) {
        // 强关联
        for (let i = 0; i < orderPointArr.length; i++) {
          let point = orderPointArr[i]
          let temp = forcePointArr.find(tmp => tmp.id == point.id)
          let find = configPointArr.find(item => item.id == point.id)
          if (temp) {
            // 强关联
            if (find) {
              find.work_order_id = this.orderId
              point.is_relation = true
              point.relation_point.work_order_id = null
              point.relation_point = find
              find.relation_point = point
              point.relation_config_index = this.configIndex
            }
          } else {
            // 弱关联
            if (find && !point.is_relation) {
              find.work_order_id = this.orderId
              point.is_relation = true
              point.relation_point = find
              find.relation_point = point
              point.relation_config_index = this.configIndex
            }
          }
        }
      } else {
        // 弱关联
        for (let i = 0; i < orderPointArr.length; i++) {
          let point = orderPointArr[i]
          let find = configPointArr.find(item => item.id == point.id)
          if (find && !point.is_relation) {
            find.work_order_id = this.orderId
            point.is_relation = true
            point.relation_point = find
            find.relation_point = point
            point.relation_config_index = this.configIndex
          }
        }
      }
      this.conflictDialogVisible = false
    },
    /**
     * 关闭冲突弹框
     */
    closeConflictDialog() {
      this.forcePointArr = []
      this.orderPointArr = []
      this.configPointArr = []
      // 关闭关联工单弹框
      this.selectOrderDialogVisible = false
    },
    /**
     * 关闭选择工单弹框
     */
    closeSelectOrderDialog() {
      this.orderId = null
      this.configIndex = null
    }
  }
}
</script>

<style lang="scss" scoped>
.app_main {
  padding: 0 20px;
}
</style>
